import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
import { take } from 'rxjs/operators/take';
import { environment } from '../../../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {

  constructor() { }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(catchError((err) => {
      if (err.status === 404) {
        if (environment.production) {
          return ErrorObservable.create(event);
        } else {
          const cloneRequest = req.clone({
            url: req.url.replace(window.API_ROOT, window.MOCK_ROOT)
          });
          return next.handle(cloneRequest).pipe(take(2));
        }

      }
      return ErrorObservable.create(event);
    }));
  }
}
